package _2025_5_8;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class HTTPClients {
    //构造Socket
    private Socket socket;
    private String ip;
    private int port;

    //构造方法初始化变量
    public HTTPClients(String ip,int port) throws IOException {
        this.ip=ip;
        this.port=port;
        socket=new Socket(ip,port);
    }

    public String get(String url) throws IOException {
        StringBuilder request=new StringBuilder();
        request.append("GEt "+url+"\n");
        request.append("IP:"+ip+"port:"+port+"\n");
        request.append("\n");
        OutputStream outputStream= socket.getOutputStream();
        outputStream.write(request.toString().getBytes());
        //获取响应
        InputStream inputStream= socket.getInputStream();
        byte[] buffer=new byte[1024*1024];
        int n=inputStream.read(buffer);
        return new String(buffer,0,n,"utf-8");
    }

    public String post(String url,String body) throws IOException {
        StringBuilder request=new StringBuilder();
        request.append("HOSt "+url+"\n");
        request.append("IP:"+ip+"port:"+port+"\n");
        request.append("Content-length"+body.getBytes().length+"\n");
        request.append("Content-Type: text/plain\n");
        request.append("\n");
        // 构造 body
        request.append(body);
        OutputStream outputStream= socket.getOutputStream();
        outputStream.write(request.toString().getBytes());
        //获取响应
        InputStream inputStream= socket.getInputStream();
        byte[] buffer=new byte[1024*1024];
        int n=inputStream.read(buffer);
        return new String(buffer,0,n,"utf-8");
    }

    public static void main(String[] args) throws IOException {
        HTTPClient httpClient = new HTTPClient("42.192.83.143", 8080);
        String getResp = httpClient.get("/AjaxMockServer/info");
        System.out.println(getResp);
        String postResp = httpClient.post("/AjaxMockServer/info", "this is body");
        System.out.println(postResp);
    }

}
